import { CheckAns } from "./CheckAns";

namespace LeetCode0003LengthOfLongestSubstring {

    // 嗯，直接计算，没啥花里胡哨的玩意儿
    function lengthOfLongestSubstring(s: string): number {
        if (!s || s.length == 0) return 0;
        let left = 0;
        let right = 1;
        // 双指针遍历一遍即可
        while (right <= s.length) {
            const set: Set<string> = new Set(s.slice(left, right));
            if (set.size + left < right) {
                // 有重复的字符串,窗口右移
                left++;
            }
            right++;
        }
        return right - left - 1;
    };

    // 不使用数据结构，最小内存方法
    function lengthOfLongestSubstring0(s: string): number {
        if (!s || s.length == 0) return 0;
        let left = 0;
        let right = 1;
        let len = 1;
        let ans = 1;
        // 双指针遍历一遍即可
        while (right < s.length) {
            const str: string = s.slice(left, right);
            const pos: number = str.indexOf(s[right]);
            if (pos >= 0) {
                // 有重复的字符串,窗口右移
                left += pos + 1;
                len = right - left;
            }
            right++;
            len++;
            ans = Math.max(ans, len);
        }
        return ans;
    };

    // test
    const testData: { s: string, ans: number }[] = [
        { s: " ", ans: 1 },
        { s: "bbbbb", ans: 1 },
        { s: "abc", ans: 3 },
        { s: "abca", ans: 3 },
        { s: "abcb", ans: 3 },
        { s: "abcabcbb", ans: 3 },
        { s: "pwwkew", ans: 3 },
        { s: "abcddabcde", ans: 5 },
        { s: "abcdefghijklmnopqrstuvwxyzjkloling", ans: 26 }
    ];
    for (const data of testData) {
        const ans = lengthOfLongestSubstring0(data.s);
        CheckAns(data, ans);
    }
}